package com.magnate.software.manager.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.WebAsyncTask;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.Callable;

/**
 * 异步控制器
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2017/2/8 15:48
 */
@RestController
@RequestMapping("/async")
public class AsyncController {

    @RequestMapping(headers = "apiVersion=1.0", value = "/response/body", method = RequestMethod.GET)
    @ResponseBody
    public Callable<String> get() throws Exception {
        return () -> {
            Thread.sleep(2000);
            return "response body result";
        };
    }

    @RequestMapping(headers = "apiVersion=1.0", value = "/view", method = RequestMethod.GET)
    public Callable<ModelAndView> callableWithView() {
        return () -> {
            Thread.sleep(2000);
            ModelAndView view = new ModelAndView();
            view.addObject("foo", "bar");
            view.addObject("fruit", "apple");
            view.setViewName("views/html");
            return view;
        };
    }

    @RequestMapping("/exception")
    @ResponseBody
    public Callable<String> callableWithException(@RequestParam(required = false, defaultValue = "true") boolean handled) throws Exception {
        return () -> {
            Thread.sleep(2000);
            if (handled) {
                // see handleException method further below
                throw new IllegalStateException("Callable error");
            } else {
                throw new IllegalArgumentException("Callable error");
            }
        };
    }

    @RequestMapping("/custom-timeout-handling")
    @ResponseBody
    public WebAsyncTask<String> callableWithCustomTimeoutHandling() throws Exception {
        Callable<String> callable = () -> {
            Thread.sleep(2000);
            return "Callable result";
        };

        return new WebAsyncTask(1000, callable);
    }

    @ExceptionHandler
    @ResponseBody
    public String handleException(IllegalStateException ex) {
        ex.printStackTrace();
        return "Handled exception: " + ex.getMessage();
    }

}
